package com.yt.user.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yt.user.models.dto.SysAdminDTO;
import com.yt.user.models.entity.SysAdmin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yt.user.server.mapper.SysAdminMapper;
import com.yt.common.utils.Md5Utils;
import com.yt.user.models.service.IUserSysAdminRemoteService;

/**
 * SysAdminRemoteService的本地回退实现
 */
@Service
public class SysAdminFallbackServiceImpl extends ServiceImpl<SysAdminMapper, SysAdmin> implements IUserSysAdminRemoteService {
    
    private static final Logger log = LoggerFactory.getLogger(SysAdminFallbackServiceImpl.class);

    @Override
    public SysAdminDTO getByUsername(String username) {
        log.warn("使用本地回退实现查询管理员信息。用户名: {}", username);
        // 在远程服务不可用时，使用本地mapper查询作为备用方案
        try {
            QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            queryWrapper.eq("is_delete", 0);
            SysAdmin admin = this.getOne(queryWrapper);
            if (admin == null) {
                return null;
            }
            
            SysAdminDTO adminDTO = new SysAdminDTO();
            BeanUtils.copyProperties(admin, adminDTO);
            adminDTO.setAdminId(admin.getAdminId());
            return adminDTO;
        } catch (Exception e) {
            log.error("本地查询管理员信息失败: ", e);
            return null;
        }
    }
    
    /**
     * 根据用户名更新管理员密码
     * @param username 用户名
     * @param newPassword 新密码
     * @return 是否更新成功
     */
    @Override
    public boolean updatePasswordByUsername(String username, String newPassword) {
        log.warn("使用本地回退实现更新管理员密码。用户名: {}", username);
        try {
            QueryWrapper<SysAdmin> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", username);
            queryWrapper.eq("is_delete", 0);
            SysAdmin admin = this.getOne(queryWrapper);
            
            if (admin == null) {
                return false;
            }
            
            // 加密新密码
            String encryptedPassword = Md5Utils.MD5Encode(newPassword);
            admin.setPassword(encryptedPassword);
            
            // 更新数据库
            return this.updateById(admin);
        } catch (Exception e) {
            log.error("本地更新管理员密码失败: ", e);
            return false;
        }
    }
}